define(["style", "echarts", "control"],function (style, echarts, control) {
    var UniqueValue = {
        layers:[],
        charts: [],

        addLayer: function (type, layerData, styleData) {
            var self = this;
            if(type==="heatmap"){
                self.addHeatMapLayer(layerData, styleData);
            } else if(type==="chartmap"){
                self.addChartMapLayer(layerData, styleData);
            } else{
                self.addThemeLayer(type, layerData, styleData);
            }
        },

        /**
         * 添加热力图
         * @param layerData
         * @param styleData
         */
        addHeatMapLayer: function (layerData, styleData) {
            var self = this;
            var vecSource = null;
            if(layerData.url){
                vecSource = new ol.source.Vector({
                    url:layerData.url,
                    format: new ol.format.GeoJSON()
                });
            } else {
                var features = (new ol.format.GeoJSON()).readFeatures(layerData.data);
                //进行坐标转换
                for(var i=0, len=features.length;i<len;i++){
                    features[i].getGeometry().transform("EPSG:4326", require("map").mapConfig.projection);
                }
                vecSource = new ol.source.Vector({
                    features: features
                });
            }
            var vecLayer = new ol.layer.Heatmap({
                source: vecSource,
                blur: styleData.blur? styleData.blur: 50,
                radius: styleData.radius? styleData.radius: 30,
                opacity:1,
                shadow:styleData.shadow? styleData.shadow: 500,
                gradient: styleData.gradient? styleData.gradient: null
            });

            require("map").map.addLayer(vecLayer);
            self.layers.push(vecLayer);

            var legendData = {
                "id": "heatmapLayer",
                "layer": vecLayer,
                "title": layerData.title,
                "colors": []
            };
            control.legendControl.addLegend(legendData);
        },

        /**
         * 添加地图统计图
         * @param layerData
         * @param styleData
         */
        addChartMapLayer: function (layerData, styleData) {
            var self = this;

            var chartData = [];
            if(layerData.url){
                $.ajax({
                    url: layerData.url,
                    async: false,
                    success: function (result) {
                        chartData = result;
                    },
                    error: function (err) {
                        console.error(err);
                    }
                });
            } else {
                chartData = layerData.data;
            }
            for(var i=0, len=chartData.length;i<len;i++){
                var size = styleData.type==="bar"?[30, 60]:[50, 50];
                size = styleData.size?styleData.size:size;

                var chartDom = $("<div/>").css({
                    width: size[1]+"px",
                    height: size[0]+"px"
                }).addClass("map-chart");
                $(require("map").map.getTargetElement()).append(chartDom);

                var lonLat = [parseFloat(chartData[i].lon), parseFloat(chartData[i].lat)];
                var coord = ol.proj.transform(lonLat, "EPSG:4326", require("map").mapConfig.projection);
                var chart = new ol.Overlay({
                    element: chartDom[0],
                    positioning: "center-center"
                });
                require("map").map.addOverlay(chart);

                var mapChart = echarts.init(chartDom[0]);

                var option = null;
                if(styleData.type==="pie"){
                    var data = [];
                    for(var item in styleData.fields){
                        data.push({
                            name: styleData.fields[item],
                            value: parseFloat(chartData[i][item])
                        })
                    }
                    option = {
                        renderAsImage:true,
                        animation: false,
                        tooltip : {
                            trigger: 'item',
                            formatter: "{b}:{c}"
                        },
                        series: [
                            {
                                type:'pie',
                                radius : '100%',
                                center: ['50%', '50%'],
                                itemStyle:{
                                    normal: {
                                        labelLine:{show: false}
                                    }
                                },
                                data: data,
                                line:false
                            }
                        ]
                    };
                } else {
                    var xData = [],
                        data = [];
                    for(var item in styleData.fields){
                        xData.push(styleData.fields[item]);
                        data.push(parseFloat(chartData[i][item]));
                    }
                    option = {
                        renderAsImage:true,
                        animation: false,
                        tooltip : {
                            trigger: 'axis'
                        },
                        grid: {
                            top: "3%",
                            left: "3%",
                            right: "3%",
                            bottom: "3%",
                            containLabel: true
                        },
                        xAxis : [{
                            type : 'category',
                            show: false,
                            data : xData,
                            axisTick: {
                                alignWithLabel: true
                            }
                        }],
                        yAxis : [{
                            show: false,
                            type : 'value'
                        }],
                        series : [{
                            name: '',
                            type: styleData.type,
                            barWidth: '80%',
                            data: data
                        }]
                    }
                }
                mapChart.setOption(option);

                chart.setPosition(coord);
                self.charts.push(chart);
            }
        },

        /**
         * 添加唯一值渲染图层
         * @param layerData {data:[], url:""}, url优先, 接受数据格式geojson
         * @param type
         * @param styleData
         */
        addThemeLayer: function (type, layerData, styleData) {
            var self = this;
            var vecSource = null;
            if(layerData.url){
                vecSource = new ol.source.Vector({
                    url:layerData.url,
                    format: new ol.format.GeoJSON()
                });
            } else {
                var features = (new ol.format.GeoJSON()).readFeatures(layerData.data);
                //进行坐标转换
                for(var i=0, len=features.length;i<len;i++){
                    features[i].getGeometry().transform("EPSG:4326", require("map").mapConfig.projection);
                }
                vecSource = new ol.source.Vector({
                    features: features
                });
            }
            var vecLayer = new ol.layer.Vector({
                renderMode: "image",//image, vector
                source: vecSource,
                style: function (feature) {
                    return style.themeLayerStyle(type, feature, styleData);
                }
            });
            require("map").map.addLayer(vecLayer);
            self.layers.push(vecLayer);

            var colors = [];
            for(var item in styleData.colorMap){
                colors.push({
                    "label": item,
                    "color": styleData.colorMap[item]
                })
            }
            var legendData = {
                "id": type+"Layer",
                "layer": vecLayer,
                "title": layerData.title,
                "colors": colors
            };
            control.legendControl.addLegend(legendData);
        },
        
        clear: function () {
            var self = this;
            for(var i=0,il=self.layers.length;i<il;i++){
                require("map").map.removeLayer(self.layers[i]);
            }
            for(var j=0,jl=self.charts.length;j<jl;j++){
                require("map").map.removeOverlay(self.charts[j]);
            }
        }
    };

    return UniqueValue;
});